package com.newworld.dmsapp2.activity.designtask.adapter;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Vector;

import org.json.JSONObject;
import org.litepal.crud.DataSupport;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.Paint;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.newworld.dmsapp2.R;
import com.newworld.dmsapp2.activity.designtask.SelectServerActivity;
import com.newworld.dmsapp2.bean.InitOperation;
import com.newworld.dmsapp2.bean.Server;
import com.newworld.dmsapp2.bean.Task;
import com.newworld.dmsapp2.bean.User;
import com.newworld.dmsapp2.ui.view.CustomDialog;
import com.newworld.dmsapp2.ui.view.CustomLoadingDialog;
import com.newworld.dmsapp2.util.Config;
import com.newworld.dmsapp2.util.HttpUtil;
import com.newworld.dmsapp2.util.SingleSample;
import com.newworld.dmsapp2.util.Tool;

/**
 * 
 * @author long 全部服务人员的adapter
 * 
 */

public class ServerAdapter extends BaseExpandableListAdapter {

	private LayoutInflater inflater;
	private SelectServerActivity context;
	private User user;
	// 被选中的服务人员
	private Server server;
	Server s = new Server();
	private Vector<Vector<Server>> serverAllList = new Vector<Vector<Server>>();
	private String[] serverType;
	private List<String> serverTypelist = new ArrayList<String>();
	private CustomLoadingDialog uploadingdialog;
	
	private String functionCode;
	private String repairId;
	private String houseId;
	private String peopleType;
	private String taskstate;
	private boolean isSingleFlag;
	
	private InitOperation initOP;
	private String sessionId;
	private Task task;
	
	Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			switch (msg.what) {

			case Config.HANDLER_MSG_POST_SUCCESS:
				if (uploadingdialog.isShowing()) {
					uploadingdialog.dismiss();
				} else {
					uploadingdialog.show();
				}

				DataSupport.deleteAll(Task.class, "repairId = ?",repairId);
				Toast.makeText(context, (String) msg.obj, Toast.LENGTH_SHORT)
						.show();
				context.finish();

				break;

			case Config.HANDLER_MSG_FAIL:
				if (uploadingdialog != null) {
					if (uploadingdialog.isShowing()) {
						uploadingdialog.dismiss();
					} else {
						uploadingdialog.show();
					}
				}
				Toast.makeText(context, (String) msg.obj, Toast.LENGTH_SHORT)
						.show();
				break;
			default:
				break;
			}

			super.handleMessage(msg);
		}
	};
	
	// 构造方法
			public ServerAdapter(SelectServerActivity context, List<Server> serverList,
					Server server, InitOperation initOP,Task task) {
				this.context = context;
				this.server = server;
				this.task = task;
				this.initOP = initOP;
				user = SingleSample.getInstance(context).getUser();
				if (null != user) {
					if (null != user.getSessionId()
							&& !user.getSessionId().equals("")) {
						sessionId = user.getSessionId();
					}
				}
				for (Server s : serverList) {
					serverTypelist.add(s.getJobName());
				}
				LinkedHashSet<String> h = new LinkedHashSet<String>(serverTypelist);
				serverTypelist.clear();
				serverTypelist.addAll(h);
				serverType = new String[serverTypelist.size()];
				serverTypelist.toArray(serverType);
				for (int k = 0; k < serverTypelist.size(); k++) {
					Vector<Server> vs = new Vector<Server>();
					serverAllList.add(vs);
				}
				for (Server s : serverList) {
					for (int i = 0; i < serverType.length; i++) {
						if (s.getJobName().equals(serverType[i])) {
							serverAllList.get(i).add(s);
						}
					}
				}
				inflater = LayoutInflater.from(context);

			}
	/*// 构造方法
	public ServerAdapter(SelectServerActivity context, List<Server> serverList,Server server,
			String functionCode, String repairId,String houseId,String peopleType,String taskstate) {
		this.context = context;
		this.server = server;
		this.functionCode = functionCode;
		this.repairId = repairId;
		this.houseId = houseId;
		this.peopleType = peopleType;
		this.taskstate = taskstate;
		user = SingleSample.getInstance(context).getUser();
		for (Server s : serverList) {
			serverTypelist.add(s.getJobName());
		}
		LinkedHashSet<String> h = new LinkedHashSet<String>(serverTypelist);
		serverTypelist.clear();
		serverTypelist.addAll(h);
		serverType = new String[serverTypelist.size()];
		serverTypelist.toArray(serverType);
		for (int k = 0; k < serverTypelist.size(); k++) {
			Vector<Server> vs = new Vector<Server>();
			serverAllList.add(vs);
		}
		
		
		for (Server s : serverList) {
			for (int i = 0; i < serverType.length; i++) {
				if (s.getJobName().equals(serverType[i])) {
					serverAllList.get(i).add(s);
				}
			}
		}
		isSingleFlag = isServerSingle(serverAllList);
		
		inflater = LayoutInflater.from(context);

	}*/

	// 获取父对象的数目
	@Override
	public int getGroupCount() {
		// TODO Auto-generated method stub
		return serverType.length;
	}

	// 获取子对象的个数
	@Override
	public int getChildrenCount(int groupPosition) {
		// TODO Auto-generated method stub
		int listsize = 0;
		for (int i = 0; i < serverType.length; i++) {
			if (serverType[groupPosition].equals(serverType[i])) {
				listsize = serverAllList.get(i).size();
			}
		}
		return listsize;
	}

	// 获取父对象
	@Override
	public Object getGroup(int groupPosition) {
		// TODO Auto-generated method stub

		return serverType[groupPosition];
	}

	// 获取子对象
	@Override
	public Object getChild(int groupPosition, int childPosition) {
		// TODO Auto-generated method stub
		Server cs = null;
		for (int i = 0; i < serverType.length; i++) {
			if (serverType[groupPosition].equals(serverType[i])) {
				cs = serverAllList.get(i).get(childPosition);
			}
		}
		return cs;
	}

	// 获取父对象的id
	@Override
	public long getGroupId(int groupPosition) {
		// TODO Auto-generated method stub
		return groupPosition;
	}

	// 获取子对象的id
	@Override
	public long getChildId(int groupPosition, int childPosition) {
		// TODO Auto-generated method stub
		return childPosition;
	}

	// 指定位置相应的组视图
	@Override
	public boolean hasStableIds() {
		// TODO Auto-generated method stub
		return true;
	}

	// 父对象的布局
	@Override
	public View getGroupView(int groupPosition, boolean isExpanded,
			View convertView, ViewGroup parent) {
		// TODO Auto-generated method stub
		convertView = inflater.inflate(R.layout.adapter_server_group_item,
				parent, false);
		RelativeLayout grouply = (RelativeLayout)convertView.findViewById(R.id.re_group_layout);
		TextView groupTitleTv = (TextView) convertView
				.findViewById(R.id.tv_group_title);
		ImageView groupIconIv = (ImageView) convertView
				.findViewById(R.id.iv_group_icon);
		if(isSingleFlag){
			grouply.setVisibility(View.GONE);
		}else{
			grouply.setVisibility(View.GONE);
			if (!isExpanded) {
				groupIconIv
						.setBackgroundResource(R.drawable.expandlistview_icon_close);
			} else {
				groupIconIv
						.setBackgroundResource(R.drawable.expandlistview_icon_open);

			}
			groupTitleTv.setText(serverType[groupPosition]);
		}
		return convertView;
	}

	// 子对象的布局
	@Override
	public View getChildView(final int groupPosition, final int childPosition,
			boolean isLastChild, View convertView, ViewGroup parent) {
		// TODO Auto-generated method stub
		convertView = inflater.inflate(R.layout.adapter_server_child_item,
				parent, false);
		RelativeLayout serverInformationRv = (RelativeLayout) convertView
				.findViewById(R.id.rv_server_information);
		TextView serverNameTv = (TextView) convertView
				.findViewById(R.id.tv_server_name);
		final TextView serverPhoneTv = (TextView) convertView
				.findViewById(R.id.tv_server_phone);
		serverPhoneTv.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);

		for (int i = 0; i < serverType.length; i++) {
			if (serverType[groupPosition].equals(serverType[i])) {
				s = serverAllList.get(i).get(childPosition);
			}
		}
		if(isSingleFlag){
			serverNameTv.setText(serverType[groupPosition]);
		}else{
			serverNameTv.setText(s.getRealName());	
		}
		
		serverPhoneTv.setText(s.getMobilePhone());
		if (server != null && server.getUserId().equals(s.getUserId())) {
			serverPhoneTv.setTextColor(Color.RED);
			serverNameTv.setTextColor(Color.RED);
		}
		// 拨打电话
		serverPhoneTv.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:"
						+ serverAllList.get(groupPosition).get(childPosition)
								.getMobilePhone()));
				context.startActivity(intent);
			}
		});
		serverInformationRv.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				s = serverAllList.get(groupPosition).get(childPosition);

				if (server != null) {
					final CustomDialog dialog = new CustomDialog(context);
					dialog.setTitle("改派");
					dialog.setDetial("是否确定完成改派？");
					dialog.setLeftOnClick(new OnClickListener() {
						@Override
						public void onClick(View v) {

							dialog.dismiss();
						}
					});
					dialog.show();
					dialog.setRightOnClick(new OnClickListener() {
						@Override
						public void onClick(View v) {
							dialog.dismiss();
							uploadingdialog = new CustomLoadingDialog(context,
									"完成改派...");
							if (uploadingdialog.isShowing()) {
								uploadingdialog.dismiss();
							} else {
								uploadingdialog.show();
							}
							new Thread(postDistributeRun).start();
						}
					});
					dialog.show();

				} else {

					final CustomDialog dialog = new CustomDialog(context);
					dialog.setTitle("派单");
					dialog.setDetial("是否确定派单？");
					dialog.setLeftOnClick(new OnClickListener() {
						@Override
						public void onClick(View v) {

							dialog.dismiss();
						}
					});
					dialog.show();
					dialog.setRightOnClick(new OnClickListener() {
						@Override
						public void onClick(View v) {
							dialog.dismiss();
							uploadingdialog = new CustomLoadingDialog(context,
									"完成派单...");
							if (uploadingdialog.isShowing()) {
								uploadingdialog.dismiss();
							} else {
								uploadingdialog.show();
							}
							new Thread(postDistributeRun).start();
						}
					});
					dialog.show();

				}

			}
		});
		return convertView;
	}

	@Override
	public void onGroupCollapsed(int groupPosition) {
		// TODO Auto-generated method stub
		super.onGroupCollapsed(groupPosition);
	}

	@Override
	public void onGroupExpanded(int groupPosition) {
		// TODO Auto-generated method stub
		super.onGroupExpanded(groupPosition);
	}

	// 当选择子节点的时候，调用该方法
	@Override
	public boolean isChildSelectable(int groupPosition, int childPosition) {
		// TODO Auto-generated method stub
		return true;
	}

	Runnable postDistributeRun = new Runnable() {

		@Override
		public void run() {
			// TODO Auto-generated method stub
			postDistribute();
		}
	};
	private String message;

	// 定义发送请求的方法
	private void postDistribute() {
		if (Tool.isNetworkAvailable(context)) {
			try {
				
				/*String result = null;
				String url = null;
				Map<String, String> map = new HashMap<String, String>();
				if (functionCode
						.equals(Config.FUNCTION_REAL_GETDISPATCHTASKLIST)) {// 报修分配
					url = Config.SERVER_URL
							+ user.getFunctionlistFromUser(
									Config.FUNCTION_REAL_REPAIRDISPATCHCOMPLETE)
									.get(0).getFunctionUrl();
					map.put("functionCode",
							Config.FUNCTION_REAL_REPAIRDISPATCHCOMPLETE);

				} else if (functionCode
						.equals(Config.FUNCTION_REAL_GETREDISPATCHTASKLIST)
						|| functionCode
								.equals(Config.FUNCTION_REAL_OUTTIMEREPAIR)
						|| functionCode
								.equals(Config.FUNCTION_REAL_GETREPAIRPROGRESSLISTDISPACHER)) {// 改派、超时派单
					url = Config.SERVER_URL
							+ user.getFunctionlistFromUser(
									Config.FUNCTION_REAL_REPAIRREDISPATCHCOMPLETE)
									.get(0).getFunctionUrl();
					map.put("functionCode",
							Config.FUNCTION_REAL_REPAIRREDISPATCHCOMPLETE);
				} else if (functionCode
						.equals(Config.FUNCTION_REAL_GETMANAGERDISPATCHTASKLIST)) {// 部门主管派单
					url = Config.SERVER_URL
							+ user.getFunctionlistFromUser(
									Config.FUNCTION_REAL_MANAGERDISPATCHCOMPLETE)
									.get(0).getFunctionUrl();
					map.put("functionCode",
							Config.FUNCTION_REAL_MANAGERDISPATCHCOMPLETE);
				} else if (functionCode
						.equals(Config.FUNCTION_REAL_GETMANAGERREDISPATCHTASKLIST)
						|| functionCode
								.equals(Config.FUNCTION_REAL_OUTTIMEREPAIROFDEPART)
						|| functionCode
								.equals(Config.FUNCTION_REAL_GETREPAIRPROGRESSLISTMANAGER)) {// 部门主管改派
					url = Config.SERVER_URL
							+ user.getFunctionlistFromUser(
									Config.FUNCTION_REAL_MANAGERREDISPATCHCOMPLETE)
									.get(0).getFunctionUrl();
					map.put("functionCode",
							Config.FUNCTION_REAL_MANAGERREDISPATCHCOMPLETE);
				}else if (functionCode.equals(Config.FUNCTION_REAL_MYAPPLY)){// 我的提单
					if (peopleType.equals(Config.DEPART_DISPATCHER)) {
						if (taskstate.contains("待分配")) {
							url = Config.SERVER_URL
									+ user.getFunctionlistFromUser(
											Config.FUNCTION_REAL_MANAGERDISPATCHCOMPLETE)
											.get(0).getFunctionUrl();
							map.put("functionCode",
									Config.FUNCTION_REAL_MANAGERDISPATCHCOMPLETE);
						} else {
							url = Config.SERVER_URL
									+ user.getFunctionlistFromUser(
											Config.FUNCTION_REAL_MANAGERREDISPATCHCOMPLETE)
											.get(0).getFunctionUrl();
							map.put("functionCode",
									Config.FUNCTION_REAL_MANAGERREDISPATCHCOMPLETE);
						}
					} else {
						if (taskstate.contains("待分配")||taskstate.contains("受理")) {
							url = Config.SERVER_URL
									+ user.getFunctionlistFromUser(
											Config.FUNCTION_REAL_REPAIRDISPATCHCOMPLETE)
											.get(0).getFunctionUrl();
							map.put("functionCode",
									Config.FUNCTION_REAL_REPAIRDISPATCHCOMPLETE);
						} else {
							url = Config.SERVER_URL
									+ user.getFunctionlistFromUser(
											Config.FUNCTION_REAL_REPAIRREDISPATCHCOMPLETE)
											.get(0).getFunctionUrl();
							map.put("functionCode",
									Config.FUNCTION_REAL_REPAIRREDISPATCHCOMPLETE);
						}
						
					}

				}
				map.put("repairId", repairId);
				map.put("serverId", s.getUserId());
				if (server != null) {
					map.put("orignalServerId", server.getUserId());
				}

				map.put("houseId", houseId);
				String setsessionid = "";
				User user = SingleSample.getInstance(context).getUser();
				if (null != user) {
					if (null != user.getSessionId()
							&& !user.getSessionId().equals("")) {
						setsessionid = user.getSessionId();
					}
				}
				result = HttpUtil.postRequestSe(url, map, setsessionid);
				Log.e("完成派单的result", result);
				result = result.replace("rows", "tasks");
				message = new JSONObject(result).getString("message");
				String flag = new JSONObject(result).getString("flag");*/
				
				String result = null;
				String url = null;
				Map<String, String> map = new HashMap<String, String>();
				url = Tool.getUrlFromUrl(user, initOP.getFunctionCode());
				map.put("functionCode",initOP.getFunctionCode());
				map.put("repairId", task.getRepairId());
				map.put("serverId", s.getUserId());
				if (server != null) {
					map.put("orignalServerId", server.getUserId());
				}

				map.put("houseId", task.getHouse_id());
				
				result = HttpUtil.postRequestSe(url, map, sessionId);
				Log.e(initOP.getOperationName()+"result", result);
				message = new JSONObject(result).getString("message");
				String flag = new JSONObject(result).getString("flag");
				
				if (flag.equals(Config.CONNECT_SUCCESS2)) {
					mHandler.obtainMessage(Config.HANDLER_MSG_POST_SUCCESS,
							message).sendToTarget();// 通知主线程数据发送成功
				} else {
					mHandler.obtainMessage(Config.HANDLER_MSG_FAIL, message)
							.sendToTarget();// 通知主线程数据发送成功
				}
			} catch (Exception e) {
				Log.e("ServiceScheduleActivity", "json数据获取报错");
				message = "json数据获取报错";
				mHandler.obtainMessage(Config.HANDLER_MSG_FAIL, message)
						.sendToTarget();
				e.printStackTrace();
			}

		} else {
			message = "请设置网络";
			mHandler.obtainMessage(Config.HANDLER_MSG_FAIL, message)
					.sendToTarget();

		}
	}
	
	/**
	 * 判断每个类别是否超过一人，超过一人列表双层展开
	 * @return boolean
	 */
	private boolean isServerSingle(Vector<Vector<Server>> list){
		boolean flag = true;
		for(int i = 0;i < list.size();i++){
			if(list.get(i).size() > 1){
				flag = false;
				return flag;
			}
		}
		return flag;
	}
}
